package cn.zswltech.gruul.web.api.util;


import cn.zswltech.gruul.biz.service.CustomTreeService;
import cn.zswltech.gruul.common.dal.dao.FunctionDOMapper;
import cn.zswltech.gruul.common.entity.FunctionDO;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author: xinhao.hu
 * @date: 2022/11/10 17:21
 * @description:
 **/
@Component
public class CommonFunctionCheck {

    @Resource
    private FunctionDOMapper functionDOMapper;

    @Resource
    private CustomTreeService customTreeService;

    /**
     * 写死，公共功能分组，该分组不展示，且该分组下功能不进行功能权限校验
     */
    private static final String COMMON_CUSTOM_CODE = "publicFunc";

    public Set<String> functionSet = new HashSet<>();

    @PostConstruct
    public void init(){
        // 找到公共分组下menuId
        List<Long> menuIds = customTreeService.queryAllMenusInCustomTree(COMMON_CUSTOM_CODE);
        Example example = new Example(FunctionDO.class);
        example.createCriteria().andIn("menuId",menuIds);
        List<FunctionDO> functionDOS = functionDOMapper.selectByExample(example);
        functionSet.addAll(functionDOS.stream().map(t -> getKey(t.getMethod(),t.getPath())).collect(Collectors.toList()));
    }

    public Boolean check(String method,String servletPath){
        // 判断是否通用接口 TODO 优化 缓存
//        Example example = new Example(FunctionDO.class);
//        example.createCriteria().andEqualTo("method",method)
//                .andEqualTo("path",servletPath);
//        List<FunctionDO> list = functionDOMapper.selectByExample(example);
//        if(org.apache.commons.collections.CollectionUtils.isNotEmpty(list)){
//            for(FunctionDO function : list){
//                if(COMMON_CUSTOM_CODE.equals(customTreeService.queryFirstCustomTreeByFunctionId(function.getId()).getCode())){
//                    // 是通用接口，不进行功能权限校验
//                    return true;
//                }
//            }
//        }

        return functionSet.contains(getKey(method,servletPath));
    }

    private String getKey(String method,String path){
        return method + "^^" + path;
    }

}
